betterpm = {}

local modpath = minetest.get_modpath("betterpm")
local reply_to = {}

dofile(modpath .. "/settings.lua")
dofile(modpath .. "/chatcmdbuilder.lua")

local function formatPrefix(prefix, sender, target)
  local res, _ = prefix:gsub("{sender}", sender)
  res, _ = res:gsub("{target}", target)

  return res
end

local function sendMessage(sender, target, message)
  reply_to[sender] = target
  reply_to[target] = sender
  if minetest.get_player_by_name(target) then
    minetest.chat_send_player(target,
      minetest.colorize(betterpm.targetPrefixColor, formatPrefix(betterpm.targetPrefix, sender, target) ..
      minetest.colorize(betterpm.targetMsgColor, message)))
    minetest.chat_send_player(sender,
      minetest.colorize(betterpm.senderPrefixColor, formatPrefix(betterpm.senderPrefix, sender, target) ..
      minetest.colorize(betterpm.senderMsgColor, message)))
  else
    minetest.chat_send_player(sender, minetest.colorize("#ff0000", target .. " is not online"))
  end
end

ChatCmdBuilder.new("msg", function(cmd)
  cmd:sub(":target :message:text", function (sender, target, message)
    sendMessage(sender, target, message)
  end)
end, {
  description = "Write private messages",
  params = "<name> <message>",
})

ChatCmdBuilder.new("w", function(cmd)
  cmd:sub(":target :message:text", function (sender, target, message)
    sendMessage(sender, target, message)
  end)
end, {
  description = "Alias for /msg",
  params = "<name> <message>",
})

ChatCmdBuilder.new("r", function(cmd)
  cmd:sub(":message:text", function (sender, message)
    if reply_to[sender] ~= nil then
      reply_to[reply_to[sender]] = sender
      minetest.chat_send_player(reply_to[sender],
        minetest.colorize(betterpm.targetPrefixColor, formatPrefix(betterpm.targetPrefix, sender, reply_to[sender]) ..
        minetest.colorize(betterpm.targetMsgColor, message)))
      minetest.chat_send_player(sender,
        minetest.colorize(betterpm.senderPrefixColor, formatPrefix(betterpm.senderPrefix, sender, reply_to[sender]) ..
        minetest.colorize(betterpm.senderMsgColor, message)))
    else
      minetest.chat_send_player(sender, "You must write to someone before replying. Use /msg <name> <message>")
    end
  end)
end, {
  description = "Reply to a private message",
  params = "<message>",
})

minetest.log("action", "[BETTERPM] Mod initialised")
